<template>
  <div
    style="height: 100vh; width: 100vw; display: flex; justify-content: center"
  >
    <div style="margin-top: 100px">
      <div style="text-align: center; margin: -10px 0 10px">
        <a-switch type="round" unchecked-color="#249544" @change="switchBox">
          <template #checked>注册</template>
          <template #unchecked>登录</template>
        </a-switch>
      </div>
      <div style="position: relative; width: 600px">
        <a-card
          title="登录"
          class="loginCard cardBox"
          hoverable
          style="padding: 20px; width: 600px; position: absolute"
        >
          <a-form
            ref="loginFormRef"
            :model="loginForm"
            style="width: 500px"
            @submit="loginSubmit"
            label-align="left"
            :auto-label-width="true"
          >
            <a-form-item
              field="userAccount"
              label="账号"
              :rules="[{ required: true, message: '请输入用户名' }]"
              :validate-trigger="['change', 'input']"
            >
              <a-input
                v-model="loginForm.userAccount"
                placeholder="请输入账号"
              />
            </a-form-item>
            <a-form-item
              tooltip="密码必须大于八位"
              field="userPassword"
              label="密码"
              :rules="[
                { required: true, message: '请输入密码' },
                { minLength: 8, message: '密码不能少于八位' },
              ]"
              :validate-trigger="['change', 'input']"
            >
              <a-input-password
                v-model="loginForm.userPassword"
                placeholder="请输入密码"
              ></a-input-password>
            </a-form-item>

            <a-form-item>
              <div>
                <a-button html-type="submit" type="primary">登录</a-button>
                <a-button
                  type="outline"
                  style="margin-left: 10px"
                  @click="loginFormRef.resetFields()"
                  >清空
                </a-button>
              </div>
            </a-form-item>
          </a-form>
        </a-card>
        <a-card
          title="注册"
          class="registerCard cardBox backCard"
          hoverable
          style="padding: 20px; width: 600px; position: absolute"
        >
          <a-form
            ref="registerFormRef"
            :model="registerForm"
            style="width: 500px"
            @submit="registerSubmit"
            label-align="left"
            :auto-label-width="true"
          >
            <a-form-item
              field="userAccount"
              label="账号"
              :rules="[{ required: true, message: '请输入用户名' }]"
              :validate-trigger="['change', 'input']"
            >
              <a-input
                v-model="registerForm.userAccount"
                placeholder="请输入账号"
              />
            </a-form-item>
            <a-form-item
              tooltip="密码必须大于八位"
              field="userPassword"
              label="密码"
              :rules="[
                { required: true, message: '请输入密码' },
                { minLength: 8, message: '密码不能少于八位' },
              ]"
              :validate-trigger="['change', 'input']"
            >
              <a-input-password
                v-model="registerForm.userPassword"
                placeholder="请输入密码"
              ></a-input-password>
            </a-form-item>
            <a-form-item
              tooltip="密码必须大于八位"
              field="checkPassword"
              label="确认密码"
              :rules="[
                { required: true, message: '请输入密码' },
                { minLength: 8, message: '密码不能少于八位' },
              ]"
              :validate-trigger="['change', 'input']"
            >
              <a-input-password
                v-model="registerForm.checkPassword"
                placeholder="请输入密码"
              ></a-input-password>
            </a-form-item>

            <a-form-item>
              <div>
                <a-button html-type="submit" type="primary">登录</a-button>
                <a-button
                  type="outline"
                  style="margin-left: 10px"
                  @click="registerFormRef.resetFields()"
                  >清空
                </a-button>
              </div>
            </a-form-item>
          </a-form>
        </a-card>
      </div>
    </div>
  </div>
</template>
<script setup lang="ts">
import {
  UserControllerService,
  UserLoginRequest,
  UserRegisterRequest,
} from "../../../generated";
import { reactive, ref } from "vue";
import { Message, ValidatedError } from "@arco-design/web-vue";
import { useUserStore } from "@/store/UserStore";
import { useRouter } from "vue-router"; // 卡片切换样式

// 卡片切换样式
let switchBox = () => {
  document.querySelector(".loginCard").classList.toggle("backCard");
  document.querySelector(".registerCard").classList.toggle("backCard");
  // 切换两个卡片的backCard类
};

//#region 登录
let loginFormRef = ref();
let loginForm: UserLoginRequest = reactive({
  userAccount: "",
  userPassword: "",
});

const userStore = useUserStore();
let router = useRouter();

let loginSubmit = () => {
  loginFormRef.value.validate(
    async (errors: undefined | Record<string, ValidatedError>) => {
      if (errors === undefined) {
        // 发送请求
        let res = await UserControllerService.userLoginUsingPost(loginForm);
        console.log("res:", res);
        if (res.code === 0) {
          //   登录成功逻辑

          // 检查响应头中是否有Set-Cookie
          // const setCookieHeader = res.headers["set-cookie"];
          // console.log("Set-cookie:", setCookieHeader);
          // if (setCookieHeader) {
          //   // 解析Set-Cookie头部，这里简化处理，实际应用可能需要更复杂的解析
          //   const sessionId = setCookieHeader[0].split(";")[0].split("=")[1];
          //   // 将sessionId保存到本地存储或cookie
          //   document.cookie = `sessionId=${sessionId}`;
          // }

          // 获取当前登录用户信息
          localStorage.setItem("loginInfo", JSON.stringify(res.data));
          userStore.loginUser = res.data;

          Message.info("登录成功");
          router.push("/");
        } else {
          Message.error(res.message);
        }
      }
    }
  );
};

//#endregion

//#region 注册
let registerFormRef = ref();
let registerForm: UserRegisterRequest = reactive({
  checkPassword: "",
  userAccount: "",
  userPassword: "",
});
let registerSubmit = () => {
  registerFormRef.value.validate(
    async (errors: undefined | Record<string, ValidatedError>) => {
      if (registerForm.checkPassword !== registerForm.userPassword) {
        Message.error("两次密码不一致");
        return;
      }
      if (errors === undefined) {
        // 发送请求
        let res = await UserControllerService.userRegisterUsingPost(
          registerForm
        );
        console.log(res);
        if (res.code === 0) {
          Message.success("注册成功！");
          registerFormRef.value.resetFields();
        } else {
          Message.error(res.message);
        }
      }
    }
  );
};
//#endregion
</script>

<style scoped>
.cardBox {
  backface-visibility: hidden;
  transition: all 0.2s ease;
}

.backCard {
  transform: rotateY(180deg);
}
</style>
